package com.xianyun.site.auth.service.impl;

import com.xianyun.common.core.utils.ServletUtils;
import com.xianyun.common.core.utils.ip.IpUtils;
import com.xianyun.site.auth.common.config.system.LoginType;
import com.xianyun.site.auth.common.entity.SecurityLoginUser;
import com.xianyun.site.auth.common.entity.SystemUser;
import com.xianyun.site.auth.common.exception.LoginCheckException;
import com.xianyun.site.auth.service.ISystemUserService;
import com.xianyun.site.iblog.dto.user.data.SystemUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDateTime;

/**
 * @author mac_zyj
 */
@Slf4j
@Service
public class ISystemUserServiceImpl implements ISystemUserService {
    @Override
    public UserDetails initAndQueryUserDetails(SystemUserDTO systemUserDTO,
                                               @Valid @NotEmpty LoginType loginType) {
        if (null == systemUserDTO) {
            if (loginType.equals(LoginType.PASSWORD)){
                throw new LoginCheckException("用户名或密码错误");
            }else if (loginType.equals(LoginType.CODE)){
                throw new LoginCheckException("手机号或验证码错误");
            }
        }
        SystemUser loginUser =SystemUser.builder()
                .innerUserInfo(systemUserDTO)
                .loginIp(IpUtils.getIpAddr(ServletUtils.getRequest()))
                .loginTime(LocalDateTime.now())
                .loginType(loginType).build();
        return new SecurityLoginUser(loginUser);
    }
}
